<?php
require("../qcubed.inc.php");

class RoleManageOrgForm extends QForm {
    // Local instance of the Meta DataGrid to list Orgs
    protected $dtgOrgs;
    protected $chkEditMode;
    protected $lstRole;
    protected $pxyRemoveRole;
    protected $AuthSys;


    // Create QForm Event Handlers as Needed

//		protected function Form_Exit() {}
//		protected function Form_Load() {}
//		protected function Form_PreRender() {}
//		protected function Form_Validate() {}

    protected function Form_Run() {
        $this->AuthSys = new Perm();
        $this->AuthSys->IsManager(true);

    }

    protected function Form_Create() {
        $this->lstRole = new QListBox($this);
        $this->lstRole->Name = "Active Role";

        $objRoles = Role::LoadAll();
        if ($objRoles) foreach ($objRoles as $objRole) {

                if ($objRole->Id <> 1)
                    $this->lstRole->AddItem($objRole->Name, $objRole);
            }


        $this->chkEditMode = new QCheckBox($this);
        $this->chkEditMode->Name = "Edit Mode (<b>Disabled</b>)";
        $this->chkEditMode->AddAction(new QClickEvent(), new QAjaxAction('chkEditMode_Click'));

        // Instantiate the Meta DataGrid
        $this->dtgOrgs = new OrgDataGrid($this);

        // Style the DataGrid (if desired)
        $this->dtgOrgs->CssClass = 'datagrid';
        $this->dtgOrgs->ShowFilter = true;
        $this->dtgOrgs->AlternateRowStyle->CssClass = 'alternate';

        // Add Pagination (if desired)
        $this->dtgOrgs->Paginator = new QPaginator($this->dtgOrgs);
        $this->dtgOrgs->ItemsPerPage = 20;
        $this->dtgOrgs->SetDataBinder('dtg_Bind');

        // Use the MetaDataGrid functionality to add Columns for this datagrid

        // Create an Edit Column
        $strEditPageUrl = __VIRTUAL_DIRECTORY__ . __FORM_DRAFTS__ . '/org_edit.php';

        //Name
        $Col="";
        $Col = new QDataGridColumn('Name', '<?= $_ITEM->Name ?>', 'Width=200', array (
                        'OrderByClause' => QQ::OrderBy(QQN::Org()->Name),
                        'ReverseOrderByClause' => QQ::OrderBy(QQN::Org()->Name, false)));
        $Col->Filter = QQ::Like(QQN::Org()->Name,null);
        $Col->FilterPrefix = $Col->FilterPostfix = '%';
        $Col->FilterType = QFilterType::TextFilter;
        $Col->FilterBoxSize = 30;
        $this->dtgOrgs->AddColumn($Col);


        $Col="";
        $Col = new QDataGridColumn('Acc #', '<?= $_ITEM->OracleLink ?>', 'Width=20', array (
                        'OrderByClause' => QQ::OrderBy(QQN::Org()->OracleLink),
                        'ReverseOrderByClause' => QQ::OrderBy(QQN::Org()->OracleLink, false)));
        $Col->Filter = QQ::Like(QQN::Org()->OracleLink,null);
        $Col->FilterPrefix = $Col->FilterPostfix = '%';
        $Col->FilterType = QFilterType::TextFilter;
        $Col->FilterBoxSize = 2;
        $this->dtgOrgs->AddColumn($Col);


        //Sales
        $Col="";
        $Col = new QDataGridColumn('Sales', '<?= $_FORM->lstSales_Render($_ITEM) ?>', 'Width=50', array (
                        'OrderByClause' => QQ::OrderBy(QQN::Org()->Sales->Name),
                        'ReverseOrderByClause' => QQ::OrderBy(QQN::Org()->Sales->Name, false)),  'HtmlEntities=false' );
        $Col->Filter = QQ::Like(QQN::Org()->Sales->Name,null);
        $Col->FilterPrefix = $Col->FilterPostfix = '%';
        $Col->FilterType = QFilterType::TextFilter;
        $Col->FilterBoxSize = 7;

        $this->dtgOrgs->AddColumn($Col);
        //Consultant
        $Col="";
        $Col = new QDataGridColumn('Consultant', '<?= $_FORM->lstConsultant_Render($_ITEM) ?>', 'Width=50', array (
                        'OrderByClause' => QQ::OrderBy(QQN::Org()->Consultant->Name),
                        'ReverseOrderByClause' => QQ::OrderBy(QQN::Org()->Consultant->Name, false)),  'HtmlEntities=false' );
        $Col->Filter = QQ::Like(QQN::Org()->Consultant->Name,null);
        $Col->FilterPrefix = $Col->FilterPostfix = '%';
        $Col->FilterType = QFilterType::TextFilter;
        $Col->FilterBoxSize = 7;
        $this->dtgOrgs->AddColumn($Col);


        $Col="";
        $Col = new QDataGridColumn('Manager Roles', '<?= $_FORM->ManagerRoles_Render($_ITEM) ?>',
                'HtmlEntities=false'
        );
        //$Col->Filter = QQ::Like(QQN::Org()->RoleAsMano ,null);
        $Col->FilterPrefix = $Col->FilterPostfix = '%';
        $Col->FilterType = QFilterType::TextFilter;
        $Col->FilterBoxSize = 7;
        $this->dtgOrgs->AddColumn($Col);

        $this->dtgOrgs->AddColumn(new QDataGridColumn('Add Manager', '<?= $_FORM->renderButton($_ITEM) ?>',
                'HtmlEntities=false'
        ));

        $this->pxyRemoveRole = new QControlProxy($this);
        $this->pxyRemoveRole->AddAction(new QClickEvent(), new QConfirmAction('Are you SURE you want to delete the Role?'));
        $this->pxyRemoveRole->AddAction(new QClickEvent(), new QAjaxAction('pxyRemoveRole_Click'));

        $this->pxyRemoveRole->AddAction(new QClickEvent(), new QTerminateAction());


        //$this->dtgOrgs->MetaAddColumn(QQN::Org()->Collocter);
        /*
                          $this->dtgPersons->AddColumn(new QDataGridColumn('Full Name', '<?= $_FORM->DisplayFullName($_ITEM) ?>', 'Width=300'));
                        //$this->dtgOrgs->MetaAddColumn(QQN::Org()->Address->Country );
                         *
        */
        //$this->dtgOrgs->MetaAddColumn(QQN::Org()->Address->Governate );
        //$this->dtgOrgs->MetaAddColumn(QQN::Org()->Address->Area );


    }
    protected function dtg_Bind() {
        $optClose = array( $this->dtgOrgs->OrderByClause, $this->dtgOrgs->LimitClause);
        /*@PERM*/
        
            $this->dtgOrgs->TotalItemCount = ORG::CountAll();
            $this->dtgOrgs->DataSource = ORG::LoadAll();
        

    }

    public function renderButton(Org $objOrg) {
        $objControlId = "addButton" . $objOrg->Id;

        if (!$objControl = $this->GetControl($objControlId)) {
            $objControl = new QButton($this->dtgOrgs, $objControlId);
            $objControl->Text = "Add";

            $objControl->AddAction(new QClickEvent(), new QAjaxAction("renderButton_Click"));
            $objControl->ActionParameter = $objOrg->Id;
        }

        return $objControl->Render(false);
    }

    public function renderButton_Click($strFormId, $strControlId, $strParameter) {
        if (!$this->chkEditMode->Checked) {
            QApplication::ExecuteJavaScript("alert('Please Enable Edit Mode; If you want to add roles.');");
            return false;
        }
        else {
            $intOrgId = intval($strParameter);
            $RoleId =  $this->lstRole->SelectedValue;
            $objOrg = Org::Load($intOrgId );
            $ManageRoles = $objOrg->GetRoleAsManoArray();
            $RoleMatch=false;
            foreach ($ManageRoles as $ManageRole) {
                if ($RoleId == $ManageRole ) {
                    $RoleMatch= true;
                    break;
                }
            }

            if ($RoleMatch== false) {
                $objOrg->AssociateRoleAsMano($RoleId );
                $objOrg->Save();
                $this->dtgOrgs->Refresh();
            }
            else
                QApplication::ExecuteJavaScript("alert('Role is already a manager on this school');");

        }

    }

    protected function chkEditMode_Click() {
        if ( $this->chkEditMode->Checked )
            $this->chkEditMode->Name = "Edit Mode (<b><font color='red'>Enabled</font></b>)";
        else
            $this->chkEditMode->Name = "Edit Mode (<b>Disabled</b>)";
    }
        public function lstConsultant_Render(Org $objOrg) {
        $strControlId = 'lstConsultant' . $objOrg->Id;
        $lstConsultant = $this->GetControl($strControlId);
        if (!$lstConsultant) {
            $lstConsultant = new QListBox ($this->dtgOrgs, $strControlId);
            $lstConsultant->AddItem('- Not Set -', null);
            // Add the items for the listbox, pulling in from the Person table
            $objRoles = Role::LoadAll();
            if ($objRoles) foreach ($objRoles as $objRole)
                    $lstConsultant->AddItem($objRole->Name, $objRole->Id);
            $lstConsultant->SelectedValue = $objOrg->ConsultantId;
            $lstConsultant->ActionParameter = $objOrg->Id;
        }
        $lstConsultant->AddAction(new QChangeEvent(), new QAjaxAction('lstConsultant_Change'));
        return $lstConsultant->Render(false);
    }

    protected function lstConsultant_Change($strFormId, $strControlId, $strParameter) {
        $intOrgId = $strParameter;
        $objOrg = Org::Load($intOrgId);
        if (!$this->chkEditMode->Checked) {
            QApplication::ExecuteJavaScript("alert('Please Enable Edit Mode; If you want to change assigned roles.');");
            $this->GetControl($strControlId)->SelectedValue = $objOrg->ConsultantId;
            return false;
        }
        else {
            $objOrg->ConsultantId = $this->GetControl($strControlId)->SelectedValue;
            $objOrg->Save();
        }
    }

    public function lstSales_Render(Org $objOrg) {
        $strControlId = 'lstSales' . $objOrg->Id;
        $lstSales = $this->GetControl($strControlId);
        if (!$lstSales) {
            $lstSales = new QListBox ($this->dtgOrgs, $strControlId);
            $lstSales->AddItem('- Not Set -', null);
            // Add the items for the listbox, pulling in from the Person table
            $objRoles = Role::LoadAll();
            if ($objRoles) foreach ($objRoles as $objRole)
                    $lstSales->AddItem($objRole->Name, $objRole->Id);
            $lstSales->SelectedValue = $objOrg->SalesId;
            $lstSales->ActionParameter = $objOrg->Id;
        }
        $lstSales->AddAction(new QChangeEvent(), new QAjaxAction('lstSales_Change'));
        return $lstSales->Render(false);
    }

    protected function lstSales_Change($strFormId, $strControlId, $strParameter) {
        $intOrgId = $strParameter;
        $objOrg = Org::Load($intOrgId);
        if (!$this->chkEditMode->Checked) {
            QApplication::ExecuteJavaScript("alert('Please Enable Edit Mode; If you want to change assigned roles.');");
            $this->GetControl($strControlId)->SelectedValue = $objOrg->SalesId;
            return false;
        }
        else {
            $objOrg->SalesId = $this->GetControl($strControlId)->SelectedValue;
            $objOrg->Save();
        }
    }

    public function ManagerRoles_Render (Org $objOrg) {

        $RoleManagArray= $objOrg->GetRoleAsManoArray();
        $name="";
        foreach ($RoleManagArray as $RoleManage) {
            $strParm= $objOrg->Id . ",".  $RoleManage->Id;
            if ($name== "")
                $name = "<a href='#'" . $this->pxyRemoveRole->RenderAsEvents($strParm,false) .">". $RoleManage->Name . "</a>";

            else
                $name= $name . ",".  "<a href='#'" . $this->pxyRemoveRole->RenderAsEvents($strParm,false) .">". $RoleManage->Name . "</a>";
        }

        Return $name;
    }

    protected function pxyRemoveRole_Click($strFormId, $strControlId, $strParameter) {
        $parm = explode(",", $strParameter);
        $msg = 'Org Id='.$parm[0] .   '  Role Id=' . $parm[1] ;
        if (!$this->chkEditMode->Checked) {
            QApplication::ExecuteJavaScript("alert('Please Enable Edit Mode; If you want to Remove manager roles.');");
            return false;
        }
        else {

            $objOrg = Org::Load($parm[0]);
            $objOrg->UnassociateRoleAsMano(Role::Load($parm[1]));
            $this->dtgOrgs->Refresh();
        }

    }

}
RoleManageOrgForm::Run('RoleManageOrgForm','tpl/rolemanageorg_list.tpl.php');
?>
